import { defHttp } from '/@/utils/http/axios';
import { useMessage } from '/@/hooks/web/useMessage';

const { createConfirm } = useMessage();

enum Api {
  list = '/esign_contracts/esignContracts/list',
  save = '/esign_contracts/esignContracts/add',
  edit = '/esign_contracts/esignContracts/edit',
  deleteOne = '/esign_contracts/esignContracts/delete',
  deleteBatch = '/esign_contracts/esignContracts/deleteBatch',
  clearAll = '/esign_contracts/esignContracts/clearAll',
  importExcel = '/esign_contracts/esignContracts/importExcel',
  exportXls = '/esign_contracts/esignContracts/exportXls',
  getDescribeTemplates = '/tencent_esign/tencent_contract/tencentContractInfo/getDescribeTemplates',
}

/**
 * 导出api
 * @param params
 */
export const getExportUrl = Api.exportXls;

/**
 * 导入api
 */
export const getImportUrl = Api.importExcel;

/**
 * 列表接口
 * @param params
 */
export const list = (params) => defHttp.get({ url: Api.list, params });

/**
 * 查询医院合同
 * @param params
 */
export const getHospitalContractList = (params) => defHttp.get({ 
  url: '/hospital_contract/hospitalContract/list', 
  params: params,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  }
});

/**
 * 根据templateId查询电子签合同详情
 * @param params
 */
export const getEsignContractByTemplateId = async (params) => {
  const templateParams = {
    operatorId: '12345678911',
    operatorName: '叶娜',
    operatorTel: '18077795149',
    proxyOrganizationName: '广西安好医院有限公司',
    proxyOrganizationOpenId: 'org_anfine',
    templateId: params?.templateid
  };
  
  console.log('请求参数:', templateParams);
  const response = await getDescribeTemplates(templateParams);
  return response;
};

/**
 * 删除单个
 * @param params
 * @param handleSuccess
 */
export const deleteOne = (params,handleSuccess) => {
  return defHttp.delete({url: Api.deleteOne, params}, {joinParamsToUrl: true}).then(() => {
    handleSuccess();
  });
}

/**
 * 批量删除
 * @param params
 * @param handleSuccess
 */
export const batchDelete = (params, handleSuccess) => {
  createConfirm({
    iconType: 'warning',
    title: '确认删除',
    content: '是否删除选中数据',
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      return defHttp.delete({url: Api.deleteBatch, data: params}, {joinParamsToUrl: true}).then(() => {
        handleSuccess();
      });
    }
  });
}

/**
 * 保存或者更新
 * @param params
 * @param isUpdate
 */
export const saveOrUpdate = (params, isUpdate) => {
  let url = isUpdate ? Api.edit : Api.save;
  return defHttp.post({ url: url, params }, { isTransformResponse: false });
}

/**
 * 获取腾讯电子签模板列表
 * @param params
 */
export const getDescribeTemplates = (params) => {
  return defHttp.post({ 
    url: Api.getDescribeTemplates, 
    data: params,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
}

/**
 * 清空所有数据
 */
export const clearAllData = () => {
  return defHttp.delete({ url: Api.clearAll });
}

/**
 * 根据医院信息获取模板信息
 * @param hospital 医院名称
 */
export const getTemplateInfoByHospital = async (hospital) => {
  try {
    // 1. 根据医院查询医院合同获取templateId
    const hospitalContractParams = {
      hospitalid: hospital
    };
    const hospitalContractResponse = await getHospitalContractList(hospitalContractParams);
    
    if (!hospitalContractResponse || !hospitalContractResponse.records || hospitalContractResponse.records.length === 0) {
      throw new Error('未找到对应的医院合同');
    }
    
    const templateId = hospitalContractResponse.records[0].templateid;
    
    // 2. 根据templateId查询电子签合同获取详细信息
    const esignContractParams = {
      templateid: templateId
    };
    
    const esignContractResponse = await getEsignContractByTemplateId(esignContractParams);
   
    if (esignContractResponse.length === 0) {
      throw new Error('未找到对应的电子签合同模板');
    }
    
    const esignContract = esignContractResponse[0]; 
    
    // 3. 返回所需的模板信息
    return {
      templateId: esignContract.templateId || esignContract.templateid,
      flowName: esignContract.templateName || esignContract.templatename,
      flowDescription: esignContract.description,
      components: esignContract.components
      
    };
  } catch (error) {
    console.error('获取模板信息失败:', error);
    throw error;
  }
};

/**
 * 同步线上模板
 * @param handleSuccess
 */
export const syncOnlineTemplates = async (handleSuccess) => {
  try {
    // 同步之前先清空数据
    console.log('清空数据...');
    await clearAllData();
    console.log('数据清空完成');
    
    // 调用获取模板接口
    const templateParams = {
      operatorId: '12345678911',
      operatorName: '叶娜',
      operatorTel: '18077795149',
      proxyOrganizationName: '广西安好医院有限公司',
      proxyOrganizationOpenId: 'org_anfine'
    };
    
    console.log('请求参数:', templateParams);
    const response = await getDescribeTemplates(templateParams);
    console.log('获取模板响应:', response);
    
    // 处理数组格式的响应
    if (response && Array.isArray(response) && response.length > 0) {
      let saveCount = 0;
      // 遍历模板数组，将每个模板保存到数据库
      for (const template of response) {
        try {
          const saveParams = {
            templateid: template.templateId,
            templatename: template.templateName,
            description: template.description || ''
          };
          console.log('保存模板参数:', saveParams);
          const saveResponse = await defHttp.post({ url: Api.save, params: saveParams });
          console.log('保存响应:', saveResponse);
          saveCount++;
        } catch (saveError) {
          console.error('保存模板失败:', template, saveError);
        }
      }
      
      if (saveCount > 0) {
        handleSuccess();
        return { success: true, message: `成功同步 ${saveCount} 个模板` };
      } else {
        return { success: false, message: '所有模板保存失败' };
      }
    } else {
      return { success: false, message: '未获取到模板数据或数据格式错误' };
    }
  } catch (error) {
    console.error('同步模板失败:', error);
    return { success: false, message: '同步模板失败' };
  }
}
